package com.superbit.model.impl;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.superbit.model.feature.AuthortyService;
@Service
public class AuthortyServiceImpl implements AuthortyService {
	
	private Map<String,AuthortyConfigValue> authoritymap = new HashMap<String,AuthortyConfigValue>();
	
	@PostConstruct
	public void init(){
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("configs/authority/authority.xml");
		try{			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(is);
			NodeList moduleNodeList = doc.getElementsByTagName("authority");
			for(int i=0;i<moduleNodeList.getLength();i++){
				Node n = moduleNodeList.item(i);
				if(!(n instanceof Element)){
					continue;
				}
				Element e = (Element)n;
				String uri = e.getAttribute("uri");
				String cmd = e.getAttribute("cmd");
				String roles = e.getAttribute("roles");
				String log = e.getAttribute("log");
				if(uri==null||cmd==null){
					continue;
				}
				
				AuthortyConfigValue acv = new AuthortyConfigValue();
				acv.setCmd(cmd);
				acv.setUri(uri);
				acv.setRoles(roles);
				acv.setNeedLog("true".equals(log));
				authoritymap.put(uri+"?cmd="+cmd, acv);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
	
	@Override
	public List<String> getAuthortyRoleByURI(String uri, String cmd) {
		AuthortyConfigValue acv = authoritymap.get(uri+"?cmd="+cmd);
		if(acv==null){
			return null;
		}else{
			String roles = acv.getRoles();
			if(roles==null||roles.trim().equals("")){
				return null;
			}else{				
				return Arrays.asList(roles.split(","));
			}
		}
	}

	@Override
	public boolean hasAuthorty(String uri, String cmd, String role) {
		List<String> list = this.getAuthortyRoleByURI(uri, cmd);
		if(list==null||list.size()==0){
			return true;
		}else{
			return list.contains(role);
		}
	}

	@Override
	public boolean needLogOperation(String uri, String cmd) {
		AuthortyConfigValue acv = authoritymap.get(uri+"?cmd="+cmd);
		if(acv==null){
			return false;
		}else{
			return acv.isNeedLog();
		}
	}


	@Override
	public void updateAuthorty(String uri, String cmd, List<String> roles, boolean needLogOperation) {
		//重新加载配置文件
		init();
	}

}
